import axios, { AxiosResponse, AxiosRequestConfig, AxiosRequestHeaders } from 'axios'
import qs from "qs"
import { ElMessage } from 'element-plus'
import { ResultEnum } from "@/enums/httpEnum"
import { getTenantId, getToken } from '@/utils/login'

const axiosInstance = axios.create({
  baseURL: '',
  timeout: ResultEnum.TIMEOUT,
  withCredentials: true, // 跨域请求，允许保存cookie
})

axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig & { headers: AxiosRequestHeaders }) => {
    const TENANT_ID = getTenantId()
    // token
    const token = getToken()

    config.headers = config.headers || {}
    //租户id
    const isToken = config.headers.isToken === false

    if (token && !isToken) {
      config.headers["Authorization"] = "Bearer " + token // token
    }
    if (TENANT_ID) {
      config.headers["TENANT-ID"] = TENANT_ID // 租户ID;
    }
    // headers中配置serialize为true开启序列化
    if (config.method === "post" && config.headers.serialize) {
      // config.data = serialize(config.data)
      delete config.data.serialize
    }

    if (config.method === "get") {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: "repeat" })
      }
    }

    return config
  },
  (error: AxiosRequestConfig) => {
    Promise.reject(error)
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (res: AxiosResponse) => {
    const status = Number(res.status)
    const msg = res.data?.msg || res.data?.message || res.statusText
    if (status === undefined || status === null
      || (status !== ResultEnum.DATA_SUCCESS && status !== ResultEnum.SUCCESS)) {
      if (msg) {
        ElMessage.error(msg)
      }
      return Promise.reject(res.data)
    }
    if (!('code' in res.data)) {
      return Promise.resolve(res)
    }
    const { code } = res.data as { code: number }
    if (code === undefined || code === null
      || (+code !== ResultEnum.DATA_SUCCESS && +code !== ResultEnum.SUCCESS)) {
      if (msg) {
        ElMessage.error(msg)
      }
      return Promise.reject(res.data)
    }
    return Promise.resolve(res.data)
  },
  (error: any) => {
    const res: AxiosResponse = error.response
    const status = Number(res.status)
    const msg = res.data?.msg || res.data?.message || res.statusText
    if (status === undefined || status === null
      || (status !== ResultEnum.DATA_SUCCESS && status !== ResultEnum.SUCCESS)) {
      if (msg) {
        ElMessage.error(msg)
      }
      return Promise.reject(res.data)
    }
    const { code } = res.data as { code: number }
    if (code === undefined || code === null
      || (+code !== ResultEnum.DATA_SUCCESS && +code !== ResultEnum.SUCCESS)) {
      if (msg) {
        ElMessage.error(msg)
      }
      return Promise.reject(res.data)
    }
    Promise.reject(res.data)
  }
)

export default axiosInstance
